import config from '../api/config.js'

	
const baseURL = config.admin_base_api  // 替换为你的实际后端地址

// 请求拦截器
const requestInterceptor = (config) => {
  // 获取token
  const token = uni.getStorageSync('token')
  if (token) {
    config.header = {
      ...config.header,
      'Authorization': 'Bearer ' + token
    }
  }
  return config
}

// 响应拦截器
const responseInterceptor = (response) => {
  const res = response.data

  // 如果code不是200, 说明后端接口出错
  if (res.code !== 200) {
    uni.showToast({
      title: res.msg || '请求失败',
      icon: 'none',
      duration: 2000
    })

    // 401: 未登录或token过期
    if (res.code === 401) {
      uni.showModal({
        title: '提示',
        content: '登录状态已过期，请重新登录',
        success: function (res) {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/login/index'
            })
          }
        }
      })
    }
    return Promise.reject(res.msg || '请求失败')
  }
  return res
}

// 错误处理
const errorHandler = (error) => {
  uni.showToast({
    title: error.message || '请求失败',
    icon: 'none',
    duration: 2000
  })
  return Promise.reject(error)
}

export default {
  request (options) {
    // 处理options
    const config = {
      ...options,
      url: baseURL + options.url,
      header: {
        'Content-Type': 'application/json',
        ...options.header
      }
    }

    // 请求拦截
    const interceptedConfig = requestInterceptor(config)

    // 发起请求
    return new Promise((resolve, reject) => {
      uni.request({
        ...interceptedConfig,
        success: (response) => {
          try {
            const res = responseInterceptor(response)
            resolve(res)
          } catch (error) {
            reject(error)
          }
        },
        fail: (error) => {
          errorHandler(error)
          reject(error)
        }
      })
    })
  },

  // GET请求
  get (url, params = {}, options = {}) {
    return this.request({
      url,
      method: 'GET',
      data: params,
      ...options
    })
  },

  // POST请求
  post (url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'POST',
      data,
      ...options
    })
  }
} 